package net.longjin.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.UUID;


public class DICTokenUtil {
    /**
     * @param @param  creator jwt实体：JWT由头部(Header)、载荷(Payload)与签名(Signature)组成
     * @param @return
     * @param @throws IllegalArgumentException
     * @param @throws UnsupportedEncodingException
     * @return String
     * @throws
     * @Description: TODO 生成token
     * @author ylj
     * @date 2017年4月12日
     */
    public static String createToken(Builder creator, String userId) throws IllegalArgumentException, UnsupportedEncodingException {

        Calendar calendar = Calendar.getInstance();//当前日期

        calendar.add(Calendar.SECOND, 3600);//设置过期时间

        //String jwtId = UUID.randomUUID().toString().replace("-", "");// 生成jwtId

        String secret = UUID.randomUUID().toString().replace("-", "");// 生成密钥

        creator.withJWTId(userId);

        creator.withExpiresAt(calendar.getTime());//设置token过期时间

        //RedisUtil.set(userId, secret, ConfigParam.JWTEXPIRES);// 将jwtId作为Key,secret作为值保存到redis,设置密钥过期时间与token有效期一致

        Algorithm algorithm = Algorithm.HMAC256(secret);

        return creator.sign(algorithm);

    }

    /**
     * @param @param  userId
     * @param @return
     * @return boolean
     * @throws
     * @Description: TODO取消密钥
     * @author ylj
     * @date 2017年6月2日
     */
    public static boolean changeToken(String userId) {
        //取消密钥
        try {
            //RedisUtil.del(userId);
            return true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param @param  token
     * @param @return true表示有效，false表示无效
     * @return boolean
     * @throws
     * @Description: TODO token验证是否有效
     * @author ylj
     * @date 2017年4月12日
     */
    public static boolean verify(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            //根据jwtid冲redis数据库获取密钥
            String secret ="";
            //String secret = RedisUtil.get(jwt.getId());
            //进行验证
            Algorithm af = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(af).build();
            DecodedJWT vjwt = verifier.verify(token);
            if (jwt.getSignature().equals(vjwt.getSignature())) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public static String getClaimProperty(String token, String porperty) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim(porperty).asString();
    }

    public static void main(String[] arg) {
        try {
		   /* Algorithm algorithm = Algorithm.HMAC256("dicpsi");
		    Date d=new Date();   
		    SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");   
		    String token = JWT.create()
		        .withIssuer("admin")
		        .withClaim("isAdmin", true)
		        .withClaim("role", "system")
		        .withExpiresAt( new Date(d.getTime() + 2 * 24 * 60 * 60 * 1000))
		        .withIssuedAt(new Date())
		        .withJWTId(UUID.randomUUID().toString())
		        .sign(algorithm);
			//String token="eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0OTE4OTY1MzQsImlzcyI6ImFkbWluIiwicm9sZSI6InN5c3RlbSIsImlzQWRtaW4iOnRydWUsImp0aSI6IjE3MDE1N2U3LWJmMDAtNDVhNi1iYzc5LWRlNzQ3OWUzYmY5ZSIsImlhdCI6MTQ5MTg5NjUzNH0.51WV_5gFNCejFCqpjiKViC7JGMEoYOG6Y0ibpdDL3k8";

			    Algorithm af = Algorithm.HMAC256("dicpsi");
			    JWTVerifier verifier = JWT.require(af)
			        .withIssuer("admin")
			        .build(); //Reusable verifier instance
			    DecodedJWT jwt = verifier.verify(token);
			  
			    //System.out.print(jwt.getSignature());
*/
            System.out.print(verify("eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0OTE5Njk3ODEsImlzcyI6ImFkbWluIiwicm9sZSI6InN5c3RlbSIsImlzQWRtaW4iOnRydWUsImp0aSI6IjJmNTBiMGUwNDY5MDQ4ODhhMjc3MzE0OWViMGU5OThmIn0.zCcrgeKR8Di5ZH80KROV1a2_9bBzHeShb3b6kWRfnS0"));

        } catch (Exception e) {
            //Invalid Signing configuration / Couldn't convert Claims.
            System.out.print(e.toString());
        }
    }
}
